package cn.edu.dgut.css.sai.excel.alibaba;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 测试用控制器
 *
 * @author Sai
 * Created by Sai on 2020/4/11.
 */
@Controller
@Slf4j
@RequestMapping("excel")
public class TestController {

    // http://localhost:8080/excel/user/aaa.xls
    // filename 前端自定义
    // 导出的excel文件类型 默认是xls，如果filename的后缀是[.xlsx]，则导出类型为xlsx。
    // 后端也可以自定义导出的文件名
    @GetMapping("user/{filename}")
    ModelAndView test(@PathVariable String filename) {
        log.info("文件名：".concat(filename));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setView(EasyExcelView.buildView(this::doProcess)); // 不指定文件名，由前端的参数filename决定。
//        modelAndView.setView(EasyExcelView.buildView(this::doProcess).fileName("sai")); // 指定文件名。
        return modelAndView;
    }

    private void doProcess(Map<String, Object> stringObjectMap, ExcelWriterBuilder excelWriterBuilder) {

        UserDTO userDTO = new UserDTO();
        userDTO.setId("1");
        userDTO.setName("黎志雄");

        UserDTO userDTO1 = new UserDTO();
        userDTO1.setId("2");
        userDTO1.setName("延科");

        UserDTO userDTO2 = new UserDTO();
        userDTO2.setId("3");
        userDTO2.setName("汉维");

        List<UserDTO> userData = new ArrayList<>();
        userData.add(userDTO);
        userData.add(userDTO1);
        userData.add(userDTO2);

        excelWriterBuilder.sheet("用户表").doWrite(userData);
    }

    @Data
    static class UserDTO {
        @ExcelProperty("Id")
        private String id;
        @ExcelProperty("Name")
        private String name;
    }
}
